import axios from 'axios';
import {
	Message
} from 'element-ui'
import {
	getToken
} from '@/utils/auth'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const requests = axios.create({
	baseURL: "/api",
	timeout: 10000
});

// 请求拦截器
requests.interceptors.request.use((config) => {
	const isToken = (config.headers || {}).isToken === false
	if (getToken() && !isToken) config.headers['tokenAuthorization'] = 'Bearer' + getToken()

	// 封装对象数据
	if (config.method === 'post' || config.method === 'put') {
		config.data = typeof config.data === 'object' ? JSON.stringify(config.data) : config.data
	}

	return config;
}, err => {
	Promise.reject(err)
});

// 响应拦截器
requests.interceptors.response.use((res) => {
	// 拦截处理错误信息
	const code = res.data.code || 200;
	const msg = res.data.msg;

	if (code === 401) {
		return Promise.reject('无效的会话，请重新登录。');
	} else if (code === 500) {
		Message({
			message: msg,
			type: 'error',
			duration: 5 * 1000
		})
	} else if (code !== 200) {
		Message({
			message: msg,
			type: 'error',
			duration: 5 * 1000
		})
	} else return res.data;
}, err => {
	let {
		message
	} = err;
	if (message == "Network Error") {
		message = "后端接口连接异常";
	} else if (message.includes("timeout")) {
		message = "系统接口请求超时";
	} else if (message.includes("Request failed with status code")) {
		message = "系统接口" + message.substr(message.length - 3) + "异常";
	}
	Message({
		message: message,
		type: 'error',
		duration: 5 * 1000
	})
	return Promise.reject(err)
});

export default requests;
